// import WebApp from '@twa-dev/sdk';
import { t } from 'i18next';
import styled from 'styled-components';
import WebApp from '@twa-dev/sdk';
import gtag from '../google/analytics';
import { GtagEvent } from '../google/analytics/Event';
import { formatInitData } from './user';
import Modal from '../component/Modal';
import Telegram from './telegram';
import styles from '../component/styles.module.css'
import { TonConnectError } from '@tonconnect/ui-react';
// import { isDev } from './check';

// if (isDev()) {
//     (function () {
//         const OriginalAbortController = window.AbortController;
//         class PatchedAbortController extends OriginalAbortController {
//             abort(...args: any[]) {
//                 console.log('abort() called', this.signal.reason, args);
//                 // try {
//                 //     // super.abort(...args);
//                 // } catch (e) {
//                 //     console.error('call abort function error:', e);
//                 // }
//             }
//         }
//         window.AbortController = PatchedAbortController;
//     })();
// }

// eslint-disable-next-line react-refresh/only-export-components
const Error = styled.div`
    color: #FFFFFF;
    font-size: 1.125rem;
    text-align: center;
    white-space:pre-line;
`

class AutoCatch {
    init() {
        window.addEventListener('unhandledrejection', (e) => {
            e.promise.catch(err => {
                if (err instanceof TonConnectError) {
                    return
                } else {
                    throw e.reason
                }
            })
        })

        const ignoreMsg = (message?: string) => {
            const msg = message?.trim()
            if (!msg) {
                return true
            }

            if (msg === 'TypeError: Load failed') {
                return true
            }
            return true
        }

        const handleError = (event: ErrorEvent | string, _source?: string, _lineno?: number, _colno?: number, error?: Error) => {
            console.error('uncatch error', event, error, error instanceof TonConnectError)
            let msg = error?.message;
            if (!msg) {
                msg = typeof event === 'string' ? event : event.message
            }
            this.config();
            gtag.event(GtagEvent.Error, { message: msg || error?.stack || 'no message', type: 'uncatch' })
            if (ignoreMsg()) {
                return false
            }
            const modal = Modal.info({
                wrapClassName: styles.custom,
                height: 'auto',
                content: {
                    content: <Error>{msg}</Error>
                },
                footer: {
                    isVertical: true,
                    okText: t('error.feedback'),
                    okClick: () => {
                        Telegram.chat('Earthcoin2')
                    },
                    cancelText: t('common.cancel'),
                    cancelClick: () => {
                        modal.destroy()
                    }
                }
            })
            return false
        }
        window.addEventListener('error', handleError, true)
    }

    private config() {
        if (!gtag.hasConfig()) {
            const initData = WebApp.initData;
            if (initData) {
                try {
                    const info = formatInitData(initData)
                    const id = info.user?.id
                    id && gtag.configUser(String(id));
                } catch (error) {
                    // temp
                }
                return
            }
            gtag.configUser('defaultUserId')
        }
    }

}

const autoCatch = new AutoCatch();
autoCatch.init()
export default autoCatch